import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../common/base/toast/toast.dart';
import 'app_bar.dart';

class ImageLoader {
  static Widget extendedImageLoader(String? url,
      {int currentIndex = 0,
      ExtendedImageMode mode = ExtendedImageMode.none,
      bool cache = true,
      double radius = 0,
      BoxFit fit = BoxFit.contain,
      String? placeHolderSrc,
      BuildContext? context,
      double? width,
      double? height,

      /// 如果需要跳转到HeroImage就需要context参数
      VoidCallback? callback}) {
    void goHero() => Navigator.push(
        context!,
        MaterialPageRoute(
            builder: (context) => _HeroImage(imageUrl: url ?? "")));
    return GestureDetector(
      onTap: context == null ? null : (callback ?? goHero),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(radius),
        child: SizedBox(
          width: width,
          height: height,
          child: ExtendedImage.network(
            url ?? "",
            fit: fit,
            cache: cache,
            //enableLoadState: false,
            // mode: ExtendedImageMode.gesture,
            mode: mode,
            initGestureConfigHandler: (state) {
              return GestureConfig(
                minScale: 0.9,
                animationMinScale: 0.7,
                maxScale: 3.0,
                animationMaxScale: 3.5,
                speed: 1.0,
                inertialSpeed: 100.0,
                initialScale: 1.0,
                inPageView: false,
                initialAlignment: InitialAlignment.center,
              );
            },
            loadStateChanged: (ExtendedImageState state) {
              if (state.extendedImageLoadState == LoadState.loading) {
                return const Center(child: CupertinoActivityIndicator());
              } else if (state.extendedImageLoadState == LoadState.failed) {
                return Image.asset(
                  placeHolderSrc ?? "assets/images/image/default_image.png",
                  fit: BoxFit.cover,
                );
              } else {
                return null;
              }
            },
          ),
        ),
      ),
    );
  }

  static Widget placeHolder(
      {double radius = 0, double? width, double? height, BoxFit? fit}) {
    return extendedImageLoader(
        "https://game.gtimg.cn/images/lol/act/img/skin/big38005.jpg",
        radius: radius,
        width: width,
        height: height,
        fit: fit ?? BoxFit.cover);
  }
}

class _HeroImage extends StatelessWidget {
  final String imageUrl;

  const _HeroImage({
    Key? key,
    required this.imageUrl,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        extendBodyBehindAppBar: true,
        appBar: MyAppBar.build(context, title: ""),
        body: Column(
          children: [
            Expanded(
              child: Hero(
                  tag: imageUrl +
                      DateTime.now().millisecondsSinceEpoch.toString(),
                  child: GestureDetector(
                    onLongPress: () {
                      showModalBottomSheet(
                          context: context,
                          backgroundColor: Colors.transparent,
                          builder: (context) => sheetDialog(context, imageUrl));
                    },
                    child: ImageLoader.extendedImageLoader(imageUrl,
                        mode: ExtendedImageMode.gesture),
                  )),
            ),
          ],
        ));
  }

  Widget sheetDialog(BuildContext context, String url) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        GestureDetector(
          onTap: () => saveToPhoto(context),
          child: Container(
            margin: EdgeInsets.symmetric(horizontal: 15.w),
            width: double.infinity,
            height: 45.h,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(10.r),
                  bottomRight: Radius.circular(10.r)),
            ),
            alignment: Alignment.center,
            child: Text(
              '保存图片',
              style: TextStyle(fontSize: 17.sp, color: Colors.white),
            ),
          ),
        ),
        SizedBox(
          height: 15.h,
        ),
        GestureDetector(
          onTap: () => Navigator.pop(context),
          child: Container(
            margin: EdgeInsets.symmetric(horizontal: 15.w),
            width: double.infinity,
            height: 45.h,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10.r),
            ),
            alignment: Alignment.center,
            child: Text(
              '取消',
              style: TextStyle(fontSize: 17.sp, color: Colors.white),
            ),
          ),
        ),
        SizedBox(
          height: 15.h,
        ),
      ],
    );
  }

  void saveToPhoto(BuildContext context) async {
    final value = await checkPermission(type: Permission.storage);
    if (!value) return;
    var response = await Dio()
        .get(imageUrl, options: Options(responseType: ResponseType.bytes));
    final result =
        await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
    if (result != null && result['isSuccess']) {
      Navigator.pop(context);
      Toast.show('成功保存到相册');
    }
  }

  /// 检查权限
  Future<bool> checkPermission({required Permission type}) async {
    bool isOk = false;

    /// 检查是否有权限
    if (await type.status != PermissionStatus.granted) {
      /// 没有权限就重新请求权限
      PermissionStatus status = await type.request();
      if (status == PermissionStatus.granted) {
        isOk = true;
      } else {
        await openAppSettings();
      }
    } else {
      isOk = true;
    }
    return isOk;
  }
}
